#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <string.h>

using namespace std;

#define BUF_SIZE 550
int main() {
    int sd=socket(AF_INET,SOCK_DGRAM,0);
    if(0>sd){
        cout<<"create socket error"<<endl;
        return -1;
    }
    struct sockaddr_in addr,cli;
    addr.sin_family=AF_INET;
//    addr.sin_addr.s_addr=inet_addr("127.0.0.1");
    addr.sin_port=htons(5683);

    if(0>bind(sd,(sockaddr*)&addr,sizeof(addr))) {
        printf("bind error\r\n");
        return -1;
    }
    socklen_t addr_len=sizeof(addr),cli_len= sizeof(cli);
    char send_buf[BUF_SIZE], recv_buf[BUF_SIZE];
    int send_len=0,recv_len=0;
    send_len=sprintf(send_buf,"%s","Hello client\n");

    for(;;){
        memset(recv_buf,0,BUF_SIZE);
        cout << "wait data" <<endl;
        recv_len=recvfrom(sd,&recv_buf,BUF_SIZE,0,(struct sockaddr*)&cli,&cli_len);
        for(int i=0;i<recv_len;i++)
            printf("%02x  ",recv_buf[i]);
        cout << "receive: "<<recv_buf <<endl;

        sendto(sd,&send_buf,send_len,0,(struct sockaddr*)&cli,cli_len);

        if(0>recv_len)
            break;

    }

    close(sd);
    cout << "disconnect" <<endl;
    return 0;
}